<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<html>

<head>
<meta http-equiv="Content-Language" content="en-us">
<title>Robot language interpreter integration tutorial</title>
<link rel="stylesheet" type="text/css" href="../style.css">
</head>

<body>

<div align="center">
<table class=allEncompassingTable >
 <tr>
  <td >
<p><a href="../index.html" TARGET="_top"><img src="images/homeImg.png"></a></p>



<h1>Robot language interpreter integration tutorial</h1>

<p>This tutorial will try to explain how to integrate or embed a robot language interpreter into CoppeliaSim. The procedure is very similar in case you want to integrate an emulator (e.g. a specific microcontroller emulator) into CoppeliaSim. Extending CoppeliaSim's functionality requires most of the time the development of a <a href="plugins.htm">plugin</a>. Make sure you have read the <a href="pluginTutorial.htm">tutorial on plugins</a> , and the <a href="externalControllerTutorial.htm">tutorial on external controllers</a> before proceeding with this tutorial.<br>
</p>

<p>The CoppeliaSim <a href="scenes.htm">scene</a> file related to this tutorial is located in CoppeliaSim's installation folder  <em>scenes\robotLanguageControl.ttt</em>. You can find the  plugin project files <a href="https://github.com/CoppeliaRobotics/simExtMTB" target="_blank">here</a>, and the server application project files <a href="https://github.com/CoppeliaRobotics/mtbServer" target="_blank">here</a>.</p>

<p>First, let's start by loading the related scene file <em>scenes\robotLanguageControl.ttt</em>:<br>
</p>

<p align=center><img src="images/robLangTut1.jpg"></p>
<br>

<p>The <em>MTB</em> robot is an imaginary robot (<em>MTB</em> stands for <em>Machine Type B</em>), that will be controlled with an imaginary robot language.</p>

<p>As previously stated, the used robot language is imaginary and very very simple. Following commands are supported (one command per line, input is case-sensitive):</p>

<pre class=lightGreyBox>
"<strong>REM</strong>" starts a comment line
"<strong>SETLINVEL</strong> v": sets the prismatic joint velocity for next movements (v is in m/s)
"<strong>SETROTVEL</strong> v": sets the revolute joint velocity for next movements (v is in degrees/s)
"<strong>MOVE</strong> p1 p2 p3 p4": moves to joint positions (p1;p2;p3;p4) (in degrees except for p3 in meters)
"<strong>WAIT</strong> x": waits x milliseconds
"<strong>SETBIT</strong> y": sets the bit at position y (1-32) in the robot output port
"<strong>CLEARBIT</strong> y": clears the bit at position y (1-32) in the robot output port
"<strong>IFBITGOTO</strong> y label": if bit at position y (1-32) in the robot input port is set, jump to &quot;label&quot;
"<strong>IFNBITGOTO</strong> y label": if bit at position y (1-32) in the robot input port is not set, jump to &quot;label&quot;
"<strong>GOTO</strong> label": jumps to "label"</pre>

<p>Any word different from &quot;<strong>REM</strong>&quot;, &quot;<strong>SETLINVEL</strong>&quot;, &quot;<strong>SETROTVEL</strong>&quot;, &quot;<strong>MOVE</strong>&quot;, &quot;<strong>WAIT</strong>&quot;, &quot;<strong>SETBIT</strong>&quot;, &quot;<strong>CLEARBIT</strong>&quot;, &quot;<strong>IFBITGOTO</strong>&quot;, &quot;<strong>IFNBITGOTO</strong>&quot; and &quot;<strong>GOTO</strong>&quot; is considered to be a label. Now run the simulation. If the related plugin was not found, following message displays (the display of the message is handled in the <a href="childScripts.htm">child scripts</a> attached to <a href="objects.htm">objects</a> <em>MTB_Robot</em> and <em>MTB_Robot#0</em>):<br>
</p>

<p align=center><img src="images/robLangTut3.jpg"></p>
<br>

<p>If the related plugin was found, then the the MTB plugin will launch a server application (i.e. <em>mtbServer</em>) that basically represents the robot language interpreter and controller. There is no direct need for a server application, the mtbServer functionality could also be directly running inside of the MTB plugin. The main advantages of using that functionality inside of a server application are:</p>

<li>The MTB plugin can act as intermediate for as many different languages as needed, also those that haven't been developed yet: the MTB plugin will simply launch the appropriate server depending on the used robot/language.</li>
<li>If the robot language interpreter / controller crashes, CoppeliaSim won't crash, since the two are distinct and separate processes.</li>


 <p>Currently, the MTB server is in charge of two main tasks:</p>
 
 <li>receive the program code (i.e. a buffer) from the MTB plugin, compile it, and initialize the robot controller.</li>
 <li>apply input signals, step through the program code (the step duration can be different from step to step), and return output signals and joint angles. </li>
 
 <p>If the MTB server detects an error during compilation of the program code, it will return an error message to the plugin, that will hand it over to the calling <a href="childScripts.htm">child script</a> (i.e. in our case, the child scripts attached to objects <em>MTB_Robot</em> and <em>MTB_Robot#0</em>.), which will display (for example):<br>
 </p>

<p align=center><img src="images/robLangTut4.jpg"></p>
<br>

<p>If the compilation was successful, then the robots start executing their respective program. The simulation is a <em>maximum speed</em> simulation, but can  be switched to real-time simulation by toggling the related toolbar button:</p>

<p align=center><img src="images/realTimeButton.jpg"></p>

<p> The execution speed can be even more accelerated by pressing the appropriate toolbar button several times:</p>

<p align=center><img src="images/simulationAcceleration.jpg"></p>

<p>Each  MTB robot  program can be individually paused, stopped or restarted at any time via their displayed custom dialog, which are <a href="customUIPlugin.htm">custom user interfaces</a>:<br>
</p>

<p align=center><img src="images/robLangTut5.jpg"></p>
<br>

<p>Above custom UI is the user-interface of the MTB robot and can be fully customized. Should the MTB robot be copied, then its custom UI will also be copied. Next to being able to controlling the program execution state, the custom UI also displays current program line (<em>Command</em>) and the MTB's current joint values. The user can also change the robot's input port bits, and read the robot's output port bits. Input and output ports can be read and respectively written by the robot language program. Input and output ports can also be written and read by external devices (e.g. the robot's gripper or suction pad) by using appropriate function calls (see further below).<br>
</p>


<p>There are two  child scripts attached to the <em>MTB_Robot</em> and <em>MTB_Robot#0</em> objects. They are in charge of handling the custom dialogs and communicating with the MTB plugin. Most code in the child scripts could be handled by the plugin too. Open the child script attached to one of the two MTB robot (e.g. with a double-click on the script icon next to the robot model in the scene hierarchy). At the top of the script, you will see the robot language code.<br>
</p>


<p>Try to modify an MTB robot's program to have it perform a different movement sequence. Experiment a little bit.</p>
<p>The MTB robots are handled in following way:</p>

<li>
the actual robot language program is compiled and executed by the &quot;mtbServer&quot; application. That application also holds the MTB robot's state variables. For each MTB robot in the simulation scene, there will be an instance of the <em>mtbServer</em> application launched by the <em>simExtMTB</em> plugin.
</li>
<li>
the <em>simExtMTB</em> plugin is in charge of providing custom Lua functions, and  also  launches the <em>mtbServer</em> application when needed, and communicates with it via socket communication.</li>
<li>
the child scripts attached to <em>MTB_Robot</em> and <em>MTB_Robot#0</em> check whether the <em>simExtMTB</em> plugin is loaded and handle the communication with the plugin. </li>



<p>The MTB robot and its simple robot language is a simple prototype meant to demonstrate how to integrate a robot language interpreter into CoppeliaSim. It is very easy to extend current functionality for much more complex robots or robot languages. All what is needed is:<br>
</p>

<li>Building the <a href="models.htm">model</a> of the robot. This includes <a href="importExport.htm">importing CAD data</a>, adding <a href="joints.htm">joints</a>, etc. This step can be entirely done in CoppeliaSim.<br>
</li>

<li>Writing a <a href="plugins.htm">plugin</a> to handle the new robot natively, i.e. to handle the new robot by interpreting its own robot language. Any language capable of accessing C-API functions and capable of being wrapped in a dll can be used to create the plugin (but c/c++ is preferred). The robot language interpreter could be directly embedded in the plugin, or launched as an external application (<em>mtbServer</em>) as is done in this tutorial.<br>
</li>

<li>Writing a small <a href="childScripts.htm">child script</a> responsible for handling <a href="customUIPlugin.htm">custom dialogs</a> and linking the robot with the plugin. This step can be entirely done in CoppeliaSim.<br>
</li>


<p>Now let's have a look at the MTB's plugin project. There is one prerequisites to embedding a robot language interpreter (or other emulator) into CoppeliaSim:<br>
</p>

<li>The robot language interpreter should be able to be executed several times in parallel. This means that several interpreter instances should be supported, in order to support several identical, in-parallel operating robots. This can be handled the easiest by launching a new interpreter for each new robot, as is done in this tutorial.<br>
</li>

<p>When writing any plugin, make sure that the plugin accesses CoppeliaSim's <a href="apiFunctions.htm">regular API</a> only from the main thread (or from a thread created by CoppeliaSim)! The plugin can launch new threads, but in that case those new threads should not be used to access CoppeliaSim (they can however be used to communicate with a server application, to communicate with some hardware, to execute background calculations, etc.).</p>
<br>

<p>Now let's have a look at the child script that is attached to the MTB robot. The code might seem quite long or complicated. However most functionality handled in the child script could also be directly handled in the plugin, making the child script much smaller/cleaner. The advantage in handling most functionality in the child script is that modifications can be performed without having to recompile the plugin!<br>
</p>

<p>Following is the MTB robot's child script main functionality:<br>
</p>

<li>
Checking whether the plugin was loaded. If not, an error message is output.</li>

<li>Communicating with the plugin. This means that information is sent to and received from the MTB plugin with custom Lua functions.<br>
</li>

<li>Applying the newly calculated joint values to the MTB robot model. This could also be handled in the MTB's plugin.<br>
</li>

<li>Reacting to events on the custom dialogs, like button presses.</li>

<li>Updating the state of the custom dialogs.<br>
</li>

<p>Following 3 custom Lua functions are of main interest (others are exported by the plugin): <br>
</p>

<pre class=lightRedBox>
number mtbServerHandle,string message=simMTB.startServer(string mtbServerExecutable,
    number portNumber,charBuffer program,table[4] jointPositions, table[2] velocities)</pre>

<pre class=lightRedBox>
number result,string message=simMTB.step(number mtbServerHandle,number timeStep)</pre>

<pre class=lightRedBox>
table[4] jointValues=simMTB.getJoints(number mtbServerHandle)</pre>


<li><strong>simMTB.startServer</strong>: launches the server application (e.g. <em>mtbServer</em>) on the specified port, connects to it, and sends it the robot language code, the initial joint positions, and the initial velocities. In return, the function returns a server handle (if successful), and a message (usually a compilation error message).</li>

<li><strong>simMTB.step</strong>: steps through the robot language program with the specified timeStep, and returns a result value and a message (usually the code being currently executed).</li>

<li><strong>simMTB.getJoints</strong>: retrieves the current joint positions. The joint positions are automatically updated when <em>simMTB.step</em> is called.</li>


<p>You could also imagine slightly modifying the step function, and add one additional function, in order to be able to handle intermediate events triggered by the robot language program execution. In that case, each simulation step would have to execute following script code (in a child script):<br>
</p>

<pre class=lightRedBox>local dt=sim.getSimulationTimeStep()
while (dt&gt;0) do
    result,dt,cmdMessage=simMTB.step(mtbServerHandle,dt) -- where the returned dt is the remaining dt
    local event=simMTB.getEvent()
    while event~=-1 do
        -- handle events here
        event=simMTB.getEvent()
    end
end</pre>





<br>
<br>

 </tr>
</table> 
</div>  
  
  
</body>

</html>
